The Tree |

本文深入探讨LeetCode中35道树相关的经典题目,包括递归与迭代方法的应用、二叉搜索树特性利用及树的遍历技巧等。不仅提供解决方案,还分享了解题思路与注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

暑期10周多实习正式结束啦!真是一段愉快而充实的经历。而我也决定申请shutterstock的全职啦。

这是一篇关于Tree的长博客。内容覆盖了Leetcode中关于Tree的35道题目。见微知著,触类旁通。

奋斗 Fighting on !


Maximum Depth of Binary Tree : DFS on one tree, return max length of left and right nodes

Minimum Depth of Binary Tree  : 

Same Tree : DFS on two trees, return whether two nodes are same or not (true or false)

Lowest Common Ancestor of a Binary Search Tree : DFS on left or right side of the tree.Use BST's property to decide which way to go or return.

Invert Binary Tree : DFS, reverse left child and right child upon each level (return)

Binary Tree Preorder Traversal 

Binary Tree Inorder Traversal

Binary Tree Postorder Traversal

Populating Next Right Pointers in Each Node: DFS , on each level, populate its child level, when populating, check if children are null

Populating Next Right Pointers in Each Node II : Iterative solution. With two queues, one for cur lvl, one for next. 

Unique Binary Search Trees : 1D DP

Unique Binary Search Trees II : ****

return value of recursion function is a list of values.

public class Solution {
    public List
  
    generateTrees(int n) {
        return helper(1,n);
    }
    public List
   
     helper(int left, int right){
        List
    
      ans = new ArrayList
     
      ();
        if(left > right){
            ans.add(null);
            return ans;
        }
        List
      
        L;
        List
       
         R; for(int i=left;i<=right;i++){ R = helper(i+1,right); L = helper(left,i-1); for(TreeNode r : R){ for(TreeNode l:L){ TreeNode node = new TreeNode(i); node.left = l; node.right = r; ans.add(node); } } } return ans; } } 
       
      
     
    
   
  

Convert Sorted Array to Binary Search Tree : Just recursively use the middle element in the array as the root node of the current tree(sub tree).
Balanced Binary Tree : Check height of subtrees of all nodes, if all satisfy the condition(difference in height is less than 2), then the whole tree is balanced.

Symmetric Tree : 

The to solve this recursively is that traverse on left and right subtree at the same time, to make left.left == right.right  and left.right == right.left

It is impossible to do it upon the origin tree recursively. Because there's a possible subproblems.

Same as "Same Tree", to be symmetric

Binary Tree Level Order Traversal II : one queue for curLvl's nodes , one queue for nxtLvl's nodes, one array to hold curLvl's values, one list of list  of values as final return result. 

Sum Root to Leaf Numbers: ***

the return condition is worthy noticing. If use  " if(node==null) " will cause problems and can't be simply fixed by dividing 2.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumNumbers(TreeNode root) {
        if(root == null){
            return 0;
        }
        int[] res = new int[1];
        helper(root,res,"");
        return res[0];
    }
    public void helper(TreeNode node,int[] res, String str){
        if(node.left == null && node.right == null){
            str += Integer.toString(node.val);
            res[0] += Integer.parseInt(str);
            return;
        }
        str += Integer.toString(node.val);
        if(node.left != null)
            helper(node.left, res, str);
        if(node.right != null)
            helper(node.right, res, str);
    }
}

Binary Tree Paths : Caution : When the binary tree is not balanced or complete tree, recursion return condition should base on "if(node.left == null && node.right == null)" and not on "if(node == null)" to iterate all possible root to leaf paths
public class Solution {
    public List
  
    binaryTreePaths(TreeNode root) {
        List
   
     ans = new ArrayList
    
     ();
        if(root == null){
            return ans;
        }
        helper(root,ans,"");
        return ans;
    }
    
    public void helper(TreeNode node, List
     
       ans, String str){
        if(str != "")
            str += "->"; 
        str += Integer.toString(node.val);
        if(node.left == null && node.right == null){
            ans.add(str);
            return;
        }
        if(node.left != null)
            helper(node.left,ans,str);
        if(node.right != null)
            helper(node.right,ans,str);
    }
}
     
    
   
  

Kth Smallest Element in a BST : in-order traversal of BST 

Path Sum

Path Sum II

*********************************************************************************************************************************************************************************

If it is not a complete tree or balanced tree, when finding all possible paths, the return condition should be "if(node.left == null && node.right == null)" !

***********************************************************************************************************************************************************************************

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class BSTIterator {
    LinkedList
  
    stack ;

    public BSTIterator(TreeNode root) {
        stack = new LinkedList
   
    ();
        while(root != null){
            stack.push(root);
            root = root.left;
        }
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode node = stack.pop();
        int res = node.val;
        if(node.right != null){
            node = node.right;
            while(node != null){
                stack.push(node);
                node = node.left;
            }
        }
        return res;
    }
}
/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */
   
  
Flatten Binary Tree to Linked List **** 

"

老套路还是用递归来解决,维护先序遍历的前一个结点pre,然后每次把pre的左结点置空,右结点设为当前结点。这里需要注意的一个问题就是我们要先把右子结点保存一下,以便等会可以进行递归,否则有可能当前结点的右结点会被覆盖,后面就取不到了。

树的题目讨论得比较多了,主要思路就是递归,考虑好递归条件和结束条件,有时候如果递归过程会对树结构进行修改的话,要先保存一下结点。

" ---Code_Ganker
This question is tough. First challenge is to find out that the order of the linked list is actually pre-order traversal. Then the next challenge is how to update pre-node in traversal. 

public class Solution {
    public void flatten(TreeNode root) {
        TreeNode[] pre = new TreeNode[1];
        pre[0] = null;
        helper(root,pre);
    }

    public void helper(TreeNode node, TreeNode[] pre){
        if(node == null)
            return;
        TreeNode right = node.right;
        if(pre[0] != null){
            pre[0].left = null;
            pre[0].right = node;
        }
       pre[0] = node;
       helper(node.left,pre);
       helper(right,pre);
    }
}

*****Another the way 

public class Solution {
    
public void flatten(TreeNode root){
    if (root == null){
        return;
    }

    flat(root, null);
} 

private TreeNode flat(TreeNode root, TreeNode post){
    if (root == null){
    return post;
    }
    TreeNode right = flat(root.right, post);
    TreeNode left = flat(root.left, right);
    root.right = left;
    root.left = null;
    return root;
    }
    
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值