天天看點

從根節點找到某一節點的路徑

1.首先判斷這個樹有沒有這個節點

bool hasNode(TreeNode root,TreeNode node){
  if(root==node) return true;
  bool has = false;
  if(root.left!=NULL) has = hasNode(root.left,node);
  if(!has && root.right!=NULL) has = hasNode(root.right,node);
  return has;
}
           

2.從根節點到某一個節點的路徑

bool getPath(TreeNode root,TreeNode node,List<TreeNode> path){
  if(root==node) return true;
  path.add(root);
  bool found = false;
  if(root.left!=NULL) found = getPath(root.left,node,path);
  if(!found && root.right!=NULL) found = getPath(root.right,node,path);
  if(!found) path.remove(path.size()-);
  retuen found;
}
           

繼續閱讀